<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Services\StockService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CancelUnpaidOrders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orders:cancel-unpaid {--minutes=30 : 取消超过指定分钟数未支付的订单}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动取消超过指定时间未支付的订单并恢复库存';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $minutes = $this->option('minutes');
        $cutoffTime = now()->subMinutes($minutes);
        
        $this->info("正在查找超过 {$minutes} 分钟未支付的订单...");
        
        // 查找待支付的订单
        $unpaidOrders = Order::where('status', Order::STATUS_PENDING)
            ->where('payment_status', Order::PAYMENT_PENDING)
            ->where('created_at', '<', $cutoffTime)
            ->with('items')
            ->get();
            
        if ($unpaidOrders->isEmpty()) {
            $this->info('没有找到需要取消的订单');
            return 0;
        }
        
        $this->info("找到 {$unpaidOrders->count()} 个需要取消的订单");
        
        $cancelledCount = 0;
        $stockService = new StockService();
        
        foreach ($unpaidOrders as $order) {
            try {
                DB::transaction(function () use ($order, $stockService) {
                    // 取消订单
                    $order->update([
                        'status' => Order::STATUS_CANCELLED,
                        'cancelled_at' => now(),
                        'cancel_reason' => "系统自动取消：超过 {$this->option('minutes')} 分钟未支付",
                    ]);
                    
                    // 恢复库存
                    foreach ($order->items as $item) {
                        $stockService->restoreStock(
                            $item->product_id,
                            $item->variant_id,
                            $item->quantity
                        );
                    }
                });
                
                $cancelledCount++;
                $this->line("已取消订单: {$order->order_number}");
                
                Log::info('Order auto-cancelled due to timeout', [
                    'order_id' => $order->id,
                    'order_number' => $order->order_number,
                    'created_at' => $order->created_at,
                    'cancelled_at' => now(),
                ]);
                
            } catch (\Exception $e) {
                $this->error("取消订单 {$order->order_number} 失败: " . $e->getMessage());
                
                Log::error('Failed to auto-cancel order', [
                    'order_id' => $order->id,
                    'order_number' => $order->order_number,
                    'error' => $e->getMessage(),
                ]);
            }
        }
        
        $this->info("成功取消 {$cancelledCount} 个订单");
        return 0;
    }
}